package com.bw.demo.controllerAdvice;

import javax.validation.ConstraintViolationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.bw.demo.model.BwResult;

@RestControllerAdvice
public class GlobalExceptionHandler 
{
	private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	enum SysErrorCodeEnum
	{
		HTTP_403("403", "抱歉出错了！请检查您输入的网址是否正确,并重新输入网址！"), HTTP_400("400", "抱歉出错了！请检查您输入参数是否正确！"), HTTP_405("405", "抱歉出错了！您访问的资源不存在！"), HTTP_406("406", "抱歉出错了！您访问的资源不存在！"), HTTP_500("500", "抱歉出错了！稍安勿躁，我们会尽快修复它！"), HTTP_501("501", "抱歉出错了！稍安勿躁，我们会尽快修复它！");
		private String code;
		private String msg;

		private SysErrorCodeEnum(String code, String msg)
		{
			this.msg = msg;
			this.code = code;
		}

		public String getMsg()
		{
			return msg;
		}

		public String getCode()
		{
			return code;
		}

	}
	// 400错误
	@ExceptionHandler(MethodArgumentNotValidException.class)
    public BwResult validateExceptionHandler(MethodArgumentNotValidException ex) {
		return resultFormat(SysErrorCodeEnum.HTTP_400.getCode(), SysErrorCodeEnum.HTTP_400.getMsg(), ex);
    }
	
	// 400错误
	@ExceptionHandler(BindException.class)
    public BwResult validateExceptionHandler(BindException ex) {
		return resultFormat(SysErrorCodeEnum.HTTP_400.getCode(), SysErrorCodeEnum.HTTP_400.getMsg(), ex);
    }
	
	// 400错误，单参数校验
	@ExceptionHandler(ConstraintViolationException.class)
    public BwResult validateExceptionHandler(ConstraintViolationException ex) {
		return resultFormat(SysErrorCodeEnum.HTTP_400.getCode(), SysErrorCodeEnum.HTTP_400.getMsg(), ex);
    }
	
	@ExceptionHandler(Exception.class)
    public BwResult exceptionHandler(Exception ex) 
	{
		return resultFormat(SysErrorCodeEnum.HTTP_500.getCode(), ex.getMessage(), ex);
    }
	
	
	protected <T extends Throwable> BwResult resultFormat(String code, String message, T ex)
	{
		logger.error("系统异常:{}{}", code, message, ex);
		return BwResult.fail(code).setMsg(message).setData("");
	}
}
